#!/usr/bin/env.python
# _*_ coding:utf-8 _*_
# # # # # # # # # # # # # # # # # # # #
#  题目:      booktest的视图           #
#  姓名:         李吉辉                #
#  时间:    2018年12月13日21:17:53     #
# # # # # # # # # # # # # # # # # # # #


# 响应
from django.http.response import HttpResponse, JsonResponse
# 视图继承的亲爹
from django.views.generic import View
# json对象
import json

# DRF框架的视图爹
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import GenericAPIView
# 模型表对象
from booktest.models import BookInfo, HeroInfo
from booktest.serializers import BookInfoSerializer, HeroInfoSerializer


from .serializers import BookInfoModelSerializer

"""
    GET     /books/         提供所有记录
    POST    /books/         新增一条记录
    GET     /books/<pk>/    提供指定id的记录
    PUT     /books/<pk>/    修改指定id的记录
    DELETE  /books/<pk>/    删除指定id的记录
    
    响应数据    JSON
"""

# 获取模型数据
# 创建序列化器并完成 【序列化】
# """序列化单个模型对象"""
# book = BookInfo.objects.get(id=1)
# serializer = BookInfoSerializer(book)
# serializer.data


"""序列化多个模型对象"""
# books = BookInfo.objects.all()
# serializer = BookInfoSerializer(instance=books, many=True)  # 注意点; 取出多个要加many=True
# serializer.data

# hero = HeroInfo.objects.get(id=1)
# hero_serializer = HeroInfoSerializer(instance=hero)
# hero_serializer.data


"""反序列化"""
# data = {"btitle": "小三国", 'bpub_date': '1999-11-10'}
# # data = {"btitle": "小三国"}
# serializer = BookInfoSerializer(data=data)
# # serializer.is_valid()  # 校验,不会自动抛出异常
# serializer.is_valid(raise_exception=True)  # 校验,自动抛出异常
#
# # serializer.errors  # 校验失败,抛出错误
# serializer.validated_data


"""反序列化【多个字段】进行额外联合校验逻辑"""
# data = {'btitle': '小三国django', 'bpub_date': '1991-11-11', 'bread': 20, 'bcomment': 30}
# serializer = BookInfoSerializer(data=data)
# serializer.is_valid(raise_exception=True)  # 如果出现异常自动抛出
# serializer.validated_data


"""反序列化之 保存到数据库"""
book = BookInfo.objects.get(id=5)
data = {'btitle': '小三国django<大三国>', 'bpub_date': '1991-11-11', 'bread': 20, 'bcomment': 10}
serializer = BookInfoSerializer(instance=book, data=data)
serializer.is_valid(raise_exception=True)  # 如果出现异常自动抛出
# 调用save(),源码中直接进行判断了,就可以执行更新和新增方法
serializer.save()  # 反序列化的 字典 转 模型 是在调用save后





class BookAPIViewSet(ModelViewSet):
    """定义视图集完成五个接口"""

    # 指定查询集 --> 查询模型的所有数据集给queryset
    queryset =  BookInfo.objects.all()

    # 指定序列化器  --> 直接类名赋值  (引用)
    serializer_class = BookInfoModelSerializer







"""下面代码是Django写的原生接口"""
# # GET/POST /books/
# class BooksAPIView(View):
#     """获取所有和新增"""
#
#     def get(self, request):
#         """获取所有书籍"""
#         # 1.查询所有数据
#         books = BookInfo.objects.all()
#
#         # 2.模型对象转字典
#         # 2.1定义一个空列表来装每本书籍的信息字典
#         book_list = []
#
#         for book in books:
#             book_dict = {
#                 "id": book.id,
#                 "btitle": book.btitle,
#                 "bpub_date": book.bpub_date,
#                 "bread": book.bread,
#                 "bcomment": book.bcomment
#             }
#             # 2.2将字典转化为列表
#             book_list.append(book_dict)
#
#         # 3.返回数据,响应                返回列表不安全
#         return JsonResponse(book_list, safe=False)
#
#     def post(self, request):
#         """新增书籍"""
#
#         # 1.提取请求体中的数据
#         # 获取前端json数据(字节流)
#         json_str_bytes = request.body
#         # 将字节流json数据转化为字符串 --> 解码
#         json_str = json_str_bytes.decode()
#
#         # 将字符串数据转化为字典/列表（loads:将字符串转化为字典, dumps-->通过json的dumps的模块可以把特定的对象序列化处理为字符串）
#         json_dict = json.loads(json_str)
#
#         # 不用字典中括号法,因为为空辉报错, 所以使用get方法来获取,当为空时会给none
#         btitle = json_dict.get("btitle")
#         bpub_date = json_dict.get("bpub_date")
#
#         # 校验参数
#         if not all([btitle, bpub_date]):
#             print("11111111111111111111参数不足")
#             return HttpResponse("参数不足", status=404)
#
#         # 2.创建模型对象并保存到数据库
#         book = BookInfo.objects.create(
#             btitle=btitle,
#             bpub_date=bpub_date,
#         )
#
#         # 3.模型对象转字典
#         book_dict = {
#             "id": book.id,
#             "btitle": book.btitle,
#             "bpub_date": book.bpub_date,
#             "bread": book.bread,
#             "bcomment": book.bcomment
#         }
#
#         # 4.返回值,响应
#         return JsonResponse(book_dict, status=201)
#
#
# class BookAPIView(View):
#     """更新/查单一/删除"""
#
#     def get(self, request, pk):
#         """查询指定的某本书"""
#
#         # 根据pk值来查
#         # 1.获取指定pk的模型
#         try:
#             book = BookInfo.objects.get(id=pk)
#         except BookInfo.DoesNotExist:
#             return HttpResponse({"message": "pk不存在"}, status=400)
#
#         # 2.模型对象转字典
#         book_dict = {
#             "id": book.id,
#             "btitle": book.btitle,
#             "bpub_date": book.bpub_date,
#             "bread": book.bread,
#             "bcomment": book.bcomment
#         }
#
#         # 3.返回值,响应
#         return JsonResponse(book_dict)
#
#     def put(self, request, pk):
#         """更新某本书籍"""
#
#         # 1.提取请求体中的数据
#         # 获取前端json数据(字节流)
#         json_str_bytes = request.body
#         # 将字节流json数据转化为字符串 --> 解码
#         json_str = json_str_bytes.decode()
#
#         # 将字符串数据转化为字典/列表（loads:将字符串转化为字典, dumps-->通过json的dumps的模块可以把特定的对象序列化处理为字符串）
#         json_dict = json.loads(json_str)
#
#         # 不用字典中括号法,因为为空会报错, 所以使用get方法来获取,当为空时会给none
#         btitle = json_dict.get("btitle")
#         bpub_date = json_dict.get("bpub_date")
#
#         # 2.校验参数
#         if not all([btitle, bpub_date]):
#             print("11111111111111111111参数不足")
#             return HttpResponse("参数不足", status=404)
#
#         # 3.获取指定pk的模型并更新
#         try:
#             BookInfo.objects.filter(id=pk).update(btitle=btitle, bpub_date=bpub_date)
#             book = BookInfo.objects.get(id=pk)
#         except BookInfo.DoesNotExist:
#             return HttpResponse({"message": "pk不存在"}, status=400)
#
#         # 4.模型对象转字典
#         book_dict = {
#             "id": book.id,
#             "btitle": book.btitle,
#             "bpub_date": book.bpub_date,
#             "bread": book.bread,
#             "bcomment": book.bcomment
#         }
#
#         # 5.返回值,响应
#         return JsonResponse(book_dict)
#
#     def delete(self, request, pk):
#         """删除指定的某本书"""
#         # 1.删除数据
#         try:
#             BookInfo.objects.get(id=pk).delete()
#         except BookInfo.DoesNotExist:
#             return HttpResponse("删除失败", status=404)
#         # 2.返回值,响应
#         return HttpResponse(status=204)
